package cn.edu.sdjzu.xg.bysj.controller;

import cn.edu.sdjzu.xg.bysj.domain.Department;
import cn.edu.sdjzu.xg.bysj.exception.BysjException;
import cn.edu.sdjzu.xg.bysj.service.DepartmentService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

    @WebServlet("/departmentDelete.ctl")
    public class DepartmentDelCtl extends HttpServlet {
        @Override
        protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 设置响应字符编码为UTF8，以便正确响应汉字
            response.setContentType("application/json;charset=UTF-8");
            // 创建JSON对象message，以便往前端响应信息
            JSONObject message_jsonObj = new JSONObject();
            // 如果请求body为空
            if (request == null) {
                message_jsonObj.put("message", "未收到请求信息！");
                response.getWriter().println(message_jsonObj);
                return;
            }
            try{
                String id_str = request.getParameter("id");
                int id = Integer.parseInt(id_str);
                Department department= DepartmentService.getInstance().find(id);
                //boolean delete = DepartmentService.getInstance().delete(id);
//                if (delete){
//                    message_jsonObj.put("message","删除成功");
//                }else {
//                    message_jsonObj.put("message","删除失败，" + department.getDescription() + "仍有系存在");
//                }
                response.getWriter().println(message_jsonObj);
            }catch (BysjException e) {
                message_jsonObj.put("message",e.getMessage());
                response.getWriter().println(message_jsonObj);
                // 每个都要有printStackTrace
                e.printStackTrace();
            }catch (SQLException e){
                message_jsonObj.put("message","数据库操作异常");
                response.getWriter().println(message_jsonObj);
                e.printStackTrace();
            }catch (Exception e){
                message_jsonObj.put("message","网络异常");
                response.getWriter().println(message_jsonObj);
                e.printStackTrace();
            }
        }
    }

